package com.googlecode.sere.translation

import scala.collection.mutable.{Map => MutableMap}
import com.googlecode.sere.util.Logging
import com.googlecode.sere.core._

object ParserRegistry extends Logging {

	private val registry = MutableMap.empty[ResourceType, MutableMap[MediaRange, Parser]]

  def register(parser: Parser, resourceType: ResourceType = NullResourceType) {
    parser.mediaRanges foreach {
      registry.getOrElseUpdate(resourceType, MutableMap.empty[MediaRange, Parser])(_) = parser
    }
  }

  def get(resourceType: ResourceType, theType: MediaType): (Option[Parser], Set[MediaRange]) = {
    logger.debug("Searching for marshaller of {} as {} in {}",
      Array(resourceType.getClass.getName, theType, registry))

    val specificParsers = registry.getOrElse(resourceType, MutableMap.empty)
    val genericParsers = registry.getOrElse(NullResourceType, MutableMap.empty)

    // Specific have priority
    val parsers = specificParsers ++ genericParsers

    val selected = parsers.find { entry =>
      val (range, _) = entry
      range.matchType(theType) > 0
    }
    selected match {
      case Some((_, parser)) => (Some(parser), Set())
      case None => {
        logger.debug("Not found any match type for {}, alternatives are {}", theType, parsers.keySet)
        (None, parsers.keySet.toSet)
      }
    }
  }
}